<!-- 设置权限菜单 -->
<template>
    <el-dialog custom-class="set-auth-menu"
        v-el-drag-dialog="{drag: true, full: false, resize: false}"
        :visible="true"
        :close-on-click-modal="false"
        @close="closeMd"
        :title="title"
        width="70%">
        <el-tabs :stretch="true" :tab-position="'top'" :value="'tab0'">
            <el-tab-pane v-for="(it, i) in menuList" :key="i" :label="it.mName" :name="'tab'+i">
                <el-tree
                    :data="[it]"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    :ref="treeRef"
                    highlight-current
                    :props="{children: 'children', label: 'mName'}"
                    :default-checked-keys="checkedList"
                ></el-tree>
            </el-tab-pane>
        </el-tabs>

        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="updAuthMenu()" :disabled="sb.load">{{sb.text}}</el-button>
            <el-button @click="closeMd">关闭</el-button>
        </div>
    </el-dialog>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog';

import * as authManageService from '@/api/services/auth.manage.service';

export default {
  name: 'SetAuthMenu',
  directives: { elDragDialog },
  props: { myData: Object },
  data() {
    return {
        // 弹框标题
        title: '',
        // 角色对象
        role: this.myData.role || null, 
        // 用户对象
        user: this.myData.user || null,
        // 线型权限菜单列表
        lineMenuList: [],
        // 树型权限菜单列表
        menuList: [],
        // 选中的复选框值列表
        checkedList: [],
        // 树型dom名称
        treeRef: 'authMenuTree',
        // 保存按钮
        sb: { load: false, text: '保存' },
    }
  },
  created(){
    const that = this;

    console.log('父级传入数据：', that.myData);
    
    that.getAuthMenuList();
  },
  methods:{
    closeMd(){ // 关闭弹框
        this.$emit('myClick', {state: false});
    },

    /**
     * 获取-线性数组中选中的值数组
     * @param lineList      欲获取的列表
     * @returns             id数组
     */
    getLineListChecked(lineList){
        const that = this;
        
        let vals = [];

        if(!lineList || lineList.length == 0) return vals;
        
        // 深度拷贝一份，防止更改源数据
        lineList = that.U.scopy(lineList);

        let map = {};
        // 遍历第一遍，以id为键，保存起来，方便获取
        lineList.forEach(it => { map[it.id] = it; });
  
        // 遍历第二遍，为父级添加子集   
        for(let it in map){
          let c = map[it], p = map[c.mPid];
  
          if(p){
            if(p.children){
                p.children.push(c);
            }else{
                p.children = [c];
            }
          }else{// 不存在，则保存为顶级
            c.children = [];
          }
        }

        for(let it in map){
            let c = map[it];
            if(c.mCheck && !c.children) vals.push(c.id);
        } 

        console.log('选中的结果', vals);

        return vals;        
    },

    // 获取-权限菜单列表
    getAuthMenuList(){
        const that = this, U = that.U;

        let loading = U.qloading('提交中，请稍后...');

        if(that.role){
            that.title = `设置【${that.role.name}】角色-功能权限`;
            authManageService.getRoleMenuList({roleId: that.role.id}).then(res => {
                U.qclose(loading);
                
                if(!res || res.code != 1){
                    U.qerror(res.msg);
                }else {
                    that.lineMenuList = res.data;
                    that.menuList = that.U.line2treeData(res.data, 'mPid');
                    that.checkedList = that.getLineListChecked(res.data);
                    console.log('角色所有权限菜单列表', that.menuList);
                }
            }).catch(() => { U.qclose(loading); });
        }else if(that.user){
            that.title = `设置【${that.user.realName}】用户-功能权限`;
            authManageService.getUserMenuList({userId: that.user.bid}).then(res => {
                U.qclose(loading);
                
                if(!res || res.code != 1){
                    U.qerror(res.msg);
                }else {
                    that.lineMenuList = res.data;
                    that.menuList = that.U.line2treeData(res.data, 'mPid');
                    that.checkedList = that.getLineListChecked(res.data);
                    console.log('用户所有权限菜单列表', that.menuList);
                }
            }).catch(() => { U.qclose(loading); });
        }
    },
    /**
     * 获取-添加/修改-权限菜单id数组
     * @param checkedIds    当前选中结果数组
     */
    getAdupMenuIds(checkedIds){
        const that = this;

        let map = {};
        that.lineMenuList.forEach(it => map[it.id] = it);

        let checkedList = []; // 结果id数组
        let getObj = function(id){
            let obj = map[id];
            if(obj){// 存在对象，则保存id
                if(checkedList.findIndex(a => a == obj.id) == -1){
                    checkedList.push(obj.id);

                    getObj(obj.mPid);
                };
            }
        };

        checkedIds.forEach(it => {
            getObj(it.id);
        });

        return checkedList;
    },
    /**
     * 更新-功能菜单
     */
    updAuthMenu(){
        const that = this, U = that.U, sb = that.sb;

        let checkedNodeList = [];
        this.$refs[that.treeRef].forEach(it => {
            checkedNodeList = checkedNodeList.concat(it.getCheckedNodes());
        }); 

        let checkedList = that.getAdupMenuIds(checkedNodeList);

        console.log('最终结果', checkedList);

        // if(checkedList.length == 0){
        //     U.qerror('请先勾选至少一项功能菜单');
        // }else{
            U.qconfim(`确定保存所选择的功能权限？`).then(r => {
                if(r){
                    if(that.role){
                        sb.load = true;
                        let loading = U.qloading('提交中，请稍后...');

                        let p = {
                            roleId: that.role.id,
                            menuIds: checkedList.join(',')
                        };
                        authManageService.addRoleMenu(p).then(res => {
                            sb.load = false;
                            U.qclose(loading);
                            
                            if(!res || res.code != 1){
                                U.qerror(res.msg);
                            }else {
                                U.qsuccess(res.msg);

                                // 关闭弹框
                                that.closeMd();
                            }
                        }).catch(() => { U.qclose(loading); });
                    }else if(that.user){
                        sb.load = true;
                        let loading = U.qloading('提交中，请稍后...');

                        let p = {
                            userId: that.user.bid,
                            menuIds: checkedList.join(',')
                        };
                        authManageService.addUserMenu(p).then(res => {
                            sb.load = false;
                            U.qclose(loading);
                            
                            if(!res || res.code != 1){
                                U.qerror(res.msg);
                            }else {
                                U.qsuccess(res.msg);

                                // 关闭弹框
                                that.closeMd();
                            }
                        }).catch(() => { U.qclose(loading); });
                    }
                }
            });
        // }
    },

  },
 }
</script>

<style lang="less" scoped>
/deep/ .el-dialog.set-auth-menu{
    height: 60vh;

    .el-dialog__body{
        overflow-y: hidden !important;

        .el-tabs__content{
            overflow-y: auto;
            height: calc(60vh - 170px);
        }
    }
}
</style>